<template>
  <el-card>
    <h3>待审批工作</h3>

    <!-- 筛选条件 -->
    <el-form :model="filters" label-width="80px" class="filter-form">
      <el-row>
        <el-col :span="8">
          <el-form-item label="员工姓名">
            <el-select v-model="filters.username" placeholder="选择员工" @change="filterWorks">
              <el-option v-for="item in employeeList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              placeholder="选择时间范围"
              @change="filterWorks"
              style="width: 250px"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8" class="reset-button-container">
          <el-form-item>
            <el-button @click="resetFilters" type="default" style="width: 100%">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 显示待审批工作 -->
    <el-table :data="paginatedWorks" border>
      <el-table-column prop="username" label="员工姓名" width="120"></el-table-column>
      <el-table-column prop="content" label="工作内容"></el-table-column>
      <el-table-column prop="createdAt" label="提交时间" width="180">
        <template #default="{ row }">
          <span>{{ formatDate(row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="success" @click="openApprovalDialog(row, '通过')">通过</el-button>
          <el-button type="danger" @click="openApprovalDialog(row, '驳回')">驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredWorks.length"
    ></el-pagination>
  </el-card>

  <!-- 审批弹窗 -->
  <el-dialog v-model="dialogVisible" title="审批工作" width="400px">
    <el-form>
      <el-form-item label="审批意见">
        <el-input v-model="approvalComment" type="textarea" placeholder="请输入审批意见"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="approveWork">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getWorkContents, approveWorkContent } from '@/api/workcontent.js'
import { ElMessage } from 'element-plus'

// 待审批工作内容
const pendingWorks = ref([])
const filteredWorks = ref([])
const filters = ref({ username: '', dateRange: [] })
const employeeList = ref([])

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10)

// 审批弹窗
const dialogVisible = ref(false)
const approvalComment = ref('')
const selectedWork = ref(null)
const approvalStatus = ref(null)

// 计算当前页显示的数据
const paginatedWorks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredWorks.value.slice(start, end)
})

// 获取待审批工作
const fetchPendingWorks = async () => {
  try {
    const departmentId = localStorage.getItem('departmentId') // 获取部门 ID
    if (!departmentId) {
      ElMessage.error('无法获取部门信息，请重新登录')
      return
    }

    const response = await getWorkContents({ departmentId }) // 传递 departmentId

    // 假设 response.data.data 是包含所有工作内容的数组
    pendingWorks.value = response.data.data.filter((item) => item.status === 'pending')
    filteredWorks.value = [...pendingWorks.value]

    // 提取员工姓名并去重
    employeeList.value = [...new Set(response.data.data.map((item) => item.username))]

  } catch (error) {
    console.error('获取待审批工作失败:', error)
    ElMessage.error('加载待审批工作失败！')
  }
}


// 筛选待审批工作
const filterWorks = () => {
  filteredWorks.value = pendingWorks.value.filter((item) => {
    let isMatch = true

    // 按员工筛选
    if (filters.value.username && item.username !== filters.value.username) {
      isMatch = false
    }

    // 按时间筛选
    if (filters.value.dateRange.length === 2) {
      const [startDate, endDate] = filters.value.dateRange
      const workDate = new Date(item.createdAt)
      if (workDate < startDate || workDate > endDate) {
        isMatch = false
      }
    }

    return isMatch
  })

  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  filters.value = { username: '', dateRange: [] }
  filterWorks()
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 打开审批弹窗
const openApprovalDialog = (row, status) => {
  selectedWork.value = row
  approvalStatus.value = status === '通过' ? 2 : 3
  approvalComment.value = ''
  dialogVisible.value = true
}

// 确认审批
const approveWork = async () => {
  if (!selectedWork.value) return

  const requestData = {
    id: selectedWork.value.id,
    status: approvalStatus.value,
    comment: approvalComment.value || (approvalStatus.value === 2 ? '审批通过' : '审批驳回'),
  }

  try {
    const response = await approveWorkContent(requestData)
    ElMessage.success(response.data.message || '审批成功')

    pendingWorks.value = pendingWorks.value.filter((item) => item.id !== selectedWork.value.id)
    filterWorks()
    dialogVisible.value = false
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('审批操作失败！')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
}

// 当前页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 组件挂载时获取数据
onMounted(fetchPendingWorks)
</script>

<style scoped>
.reset-button-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
